package org.lyg.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.lyg.domain.User;
import org.lyg.shiro.service.IPermissionService;
import org.lyg.service.IUserService;
import org.lyg.shiro.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IRoleService roleService;

    /**
     * 身份认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //从token中获取用户身份信息
        String username = (String) token.getPrincipal();
        //通过username从数据库中查询
        User user = userService.getUserByName(username);
        if (user == null) {
            return null;
        }
        //获取权限
        List<String> permissions = permissionService.findRolesByUserName(user.getName());
        user.setPermissionList(permissions);
        if (user.isDisable()){
            //账号被禁用
            throw new DisabledAccountException();
        }
        if (user.isLocked()){
            //账号被锁定
            throw new LockedAccountException();
        }

        return new SimpleAuthenticationInfo(user, user.getPwd(), getName());
    }

    /**
     * 权限认证
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        List<String> roles = roleService.findRolesByUserId(user.getId());
        info.addRoles(roles);

        List<String> perms = permissionService.findRolesByUserName(user.getName());
        info.addStringPermissions(perms);
        return info;
    }
}
